<template>
  <!-- 抽奖活动添加 -->
  <div class="commonCon">
    <div class="addBox">
      <div class="in-b btn-see" v-if="luckType=='X'">
        <el-button type="primary" @click="seeLdRecord()" v-if="LDData.id">抽奖记录</el-button>
        <el-button type="primary" @click="goPer()">抽奖人员名单</el-button>
      </div>
      <el-form :inline="luckType=='X'?true:false">
        <el-form-item label="抽奖标题" v-if="luckType!='X'">
          <el-input v-model="LDData.lotteryTitle" placeholder="标题" style="width:100%;float:left"></el-input>
        </el-form-item>
        <el-form-item label="关联赛事" v-if="luckType!='X'">
          <el-select v-model="matchIds" multiple filterable placeholder="请选择" style="width:100%">
            <el-option v-for="item in matchArr" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="需完成赛事个数" v-if="luckType!='X'">
          <el-input v-model="LDData.finishMatchNum" placeholder="需完成赛事个数"></el-input>
        </el-form-item>
        <el-form-item label="抽奖开始时间">
          <el-date-picker v-model="LDData.st" type="datetime" placeholder="选择开始日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="抽奖结束时间">
          <el-date-picker v-model="LDData.et" type="datetime" placeholder="选择结束日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <div class="tips">
        <el-input type="textarea" :rows="4" placeholder="请输入抽奖说明" v-model="LDData.lotteryRule"></el-input>
      </div>
      <div class="tabBox">
        <el-table :data="LDData.prizeInfos" border style="width: 100%">
          <el-table-column label="奖品位置">
            <template slot-scope="{ row }">
              <el-input v-model.number="row.type" placeholder="位置,例:1,2,3..."></el-input>
            </template>
          </el-table-column>
          <el-table-column label="名称">
            <template slot-scope="{ row }">
              <el-input v-model="row.name" placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="图片" align="center">
            <template slot-scope="{ row }">
              <div class="changeLogo" v-if="!row.prizeImg">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <input type="file" class="chooseIpt" @change="upLogo($event, row)" />
              </div>
              <div v-else class="seeLogo">
                <img :src="row.prizeImg" alt />
                <span class="avatar-uploader-icon">
                  <i class="el-icon-delete" @click="
                          row.prizeImg = '';
                          $forceUpdate();
                        "></i>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="发布数量" align="center">
            <template slot-scope="{ row, $index }">
              <el-input class="iptBox" v-model="row.num" placeholder="请输入内容" @input="$forceUpdate()"
                @change="pDNum($event, $index, 1)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="已抽取数量" align="center" v-if="LDData.id">
            <template slot-scope="{ row }">
              <span>{{ row.coun }}</span>
            </template>
          </el-table-column>
          <el-table-column label="概率" align="center">
            <template slot-scope="{ row, $index }">
              <el-input class="iptBox" v-model="row.prizeProb" placeholder="请输入内容" @input="$forceUpdate()"
                @change="pDNum($event, $index, 2)">
                <span slot="append" class="dw">%</span>
              </el-input>
              <!-- @input="change($event, $index)" -->
              <!-- :disabled="$index == LDData.prizeInfos.length - 1" -->
            </template>
          </el-table-column>
          <el-table-column label="是否显示" align="center">
            <template slot-scope="{ row, $index }">
              <el-radio-group v-model="row.state" @change="togState($event, $index)">
                <!-- :disabled="$index == LDData.prizeInfos.length - 1" -->
                <el-radio :label="1">是</el-radio>
                <!-- :disabled="$index == LDData.prizeInfos.length - 1" -->
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="奖品链接" align="center">
            <template slot-scope="{ row }">
              <el-input v-model="row.prizeLinks" placeholder="请输入奖品链接"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="{ row,$index }">
              <el-button type="danger" size="medium" v-if="row.wc==1" @click="delLine($index)">删除</el-button>
              <!-- <el-button type="danger" size="medium" disabled v-else>删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <p class="tabTips">
          * 该抽奖活动为九宫格抽奖，显示数量需为8条,剩余可调配概率
          <span class="sheng">&nbsp;&nbsp;&nbsp;{{Deployment}}</span>
        </p>
      </div>
      <div class="sbb">
        <el-button type="primary" @click="addJP()">添加奖品</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </div>
      <div class="demo" v-if="showP.length>0">
        <div class="item">
          <img v-if="showP[0].prizeImg" :src="showP[0].prizeImg" class="demoImg" />
          <span v-else class="noImg">奖品1</span>
        </div>
        <div class="item">
          <img v-if="showP[1].prizeImg" :src="showP[1].prizeImg" class="demoImg" />
          <span v-else class="noImg">奖品2</span>
        </div>
        <div class="item">
          <img v-if="showP[2].prizeImg" :src="showP[2].prizeImg" class="demoImg" />
          <span v-else class="noImg">奖品3</span>
        </div>
        <div class="item">
          <img v-if="showP[7].prizeImg" :src="showP[7].prizeImg" class="demoImg" />
          <span v-else class="noImg">奖品8</span>
        </div>
        <div class="item">
          <img src="../../../../static/image/luckBtn.png" class="demoImg" />
        </div>
        <div class="item">
          <img v-if="showP[3].prizeImg" :src="showP[3].prizeImg" class="demoImg" />
          <span v-else class="noImg">奖品4</span>
        </div>
        <div class="item">
          <img v-if="showP[6].prizeImg" :src="showP[6].prizeImg" class="demoImg" />
          <span v-else class="noImg">奖品7</span>
        </div>
        <div class="item">
          <img v-if="showP[5].prizeImg" :src="showP[5].prizeImg" class="demoImg" />
          <span v-else class="noImg">奖品6</span>
        </div>
        <div class="item">
          <img v-if="showP[4].prizeImg" :src="showP[4].prizeImg" class="demoImg" />
          <span v-else class="noImg">奖品5</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  /*解决两个数相加精度丢失问题*/
  const floatAdd = (a, b) => {
    var c, d, e;
    if (undefined == a || null == a || "" == a || isNaN(a)) {
      a = 0;
    }
    if (undefined == b || null == b || "" == b || isNaN(b)) {
      b = 0;
    }
    try {
      c = a.toString().split(".")[1].length;
    } catch (f) {
      c = 0;
    }
    try {
      d = b.toString().split(".")[1].length;
    } catch (f) {
      d = 0;
    }
    e = Math.pow(10, Math.max(c, d));
    return (floatMul(a, e) + floatMul(b, e)) / e;
  };
  /*解决两个数相乘精度丢失问题*/
  const floatMul = (a, b) => {
    var c = 0,
      d = a.toString(),
      e = b.toString();
    try {
      c += d.split(".")[1].length;
    } catch (f) {}
    try {
      c += e.split(".")[1].length;
    } catch (f) {}
    return (
      (Number(d.replace(".", "")) * Number(e.replace(".", ""))) / Math.pow(10, c)
    );
  };
  //判断两个时间是否有交集
  function isDateIntersection(start1, end1, start2, end2) {
    var x = new Date(start1.replace("-", "/").replace("-", "/")).getTime();
    var y = new Date(end1.replace("-", "/").replace("-", "/")).getTime();

    var a = new Date(start2.replace("-", "/").replace("-", "/")).getTime();
    var b = new Date(end2.replace("-", "/").replace("-", "/")).getTime();
    if (y < a || b < x) return false;
    else return true;
  }
  var mId = "";
  export default {
    props: {
      luckType: {
        default: 'X'
      },
      lotteryId: ''
    },
    data() {
      return {
        matchArr: [],
        matchIds: [],
        LDData: {
          lotteryRule: "",
          matchId: "",
          prizeInfos: [{
            name: "谢谢参与",
            prizeImg: "",
            num: "",
            state: 1,
            prizeProb: 100,
            type: "",
            wc: 1,
          }, ],
          et: "",
          st: "",
        },
        matchId: "",
        Deployment: 0,
        showP: [],
      };
    },
    watch: {
      lotteryId: {
        // 执行方法
        handler(n, o) {
          // console.log('newVal-----', n, o)
          this.LDData = {
            lotteryRule: "",
            matchId: "",
            prizeInfos: [{
              name: "谢谢参与",
              prizeImg: "",
              num: "",
              state: 1,
              prizeProb: 100,
              type: "",
              wc: 1,
            }, ],
            et: "",
            st: "",
          }
          if (n) {
            this.getLotteryById()
          }
        },
        deep: true, // 深度监听
        immediate: true // 第一次改变就执行
      }
    },
    methods: {
      //   数字判断
      pDNum(val, index, i) {
        // d ==> priceList
        if (isNaN(val)) {
          this.$confirm("请输入数字", "提示", {
            confirmButtonText: "确定",
            showCancelButton: false,
            showClose: false,
            closeOnClickModal: false,
            type: "warning",
          }).then(() => {
            if (i === 1) {
              this.LDData.prizeInfos[index].num = "";
            } else if (i == 2) {
              this.LDData.prizeInfos[index].prizeProb = 0;
            }
            this.$forceUpdate();
          });
        } else {
          if (i == 2) {
            let row = this.LDData;
            if (val > 100 || val < 0) {
              this.$confirm("概率为0~100%", "提示", {
                confirmButtonText: "确定",
                showCancelButton: false,
                showClose: false,
                closeOnClickModal: false,
                type: "warning",
              });
              return false;
            }
            let num = 0;
            row.prizeInfos.map((v) => {
              if (v.state == 1) {
                num = floatAdd(num, v.prizeProb);
              }
            });
            this.Deployment = 0;
            if (num < 100) {
              this.Deployment = (100 - num).toFixed(2);
            }
          } else if (i == 1) {
            let row = this.LDData;
            let sum = 0;
            row.prizeInfos.map((v) => {
              if (v.state == 1) {
                sum += parseInt(Number(v.num));
              }
            });
            let num = 0;
            row.prizeInfos.forEach((v) => {
              if (v.state == 1) {
                v.prizeProb = 0;
                if (v.num > 0) {
                  v.prizeProb = Math.ceil((Number(v.num) / sum) * 10000) / 100;
                }
                num = floatAdd(num, v.prizeProb);
              } else v.prizeProb = 0;
            });
            this.Deployment = 0;
            if (num < 100) {
              this.Deployment = (100 - num).toFixed(2);
            }
          }
        }
      },
      togState(v, i) {
        let row = this.LDData;
        let sum = 0;
        let oo = row.prizeInfos.filter((v) => v.state == 1);
        if (oo.length > 8) {
          this.$message.warning("显示数量需为8条");
          row.prizeInfos[i].state = 0;
        }
        row.prizeInfos.map((v) => {
          if (v.state == 1) {
            sum += parseInt(Number(v.num));
          } else {
            v.prizeProb = 0;
          }
        });
        let num = 0;
        // console.log(sum);
        row.prizeInfos.forEach((v) => {
          if (v.state == 1) {
            v.prizeProb = 0;
            if (v.num > 0) {
              v.prizeProb = Math.ceil((Number(v.num) / sum) * 10000) / 100;
            }
            num = floatAdd(num, v.prizeProb);
          } else v.prizeProb = 0;
        });
        this.Deployment = 0;
        if (num < 100) {
          this.Deployment = (100 - num).toFixed(2);
        }
        this.$forceUpdate();
      },
      // 上传logo
      upLogo(e, row) {
        // console.log(e, row);
        if (e) {
          row.logo = "";
          let file = e.target.files[0];
          let param = new FormData(); //创建form对象
          param.append("img", file); //通过append向form对象添加数据
          // this.$putImg(param).
          this.$axios.post("/sbr/match/uploadImg", param).then((res) => {
            // console.log(res);
            row.prizeImg = res.data.data.filePath;
            this.$forceUpdate();
          });
        }
      },
      getALd() {
        let oo = {
          matchId: mId
        };
        this.$axios
          .get("/sbr/guess/getLotteryByMatchId", {
            params: oo
          })
          .then((res) => {
            let rr = res.data.data;
            if (rr) {
              rr.et = new Date(rr.endTime);
              rr.st = new Date(rr.startTime);
              // rr.date = [new Date(rr.startTime), new Date(rr.endTime)];
              this.LDData = rr;
              let h = 0;
              rr.prizeInfos.map((v) => {
                // if (v.coun == 0) v.wc = 1;
                if (v.state == 1) {
                  h = floatAdd(h, v.prizeProb);
                }
              });
              rr.prizeInfos.forEach((v) => {
                v.type = v.type == 0 ? "" : v.type;
              });
              this.Deployment = 0;
              if (h < 100) {
                this.Deployment = (100 - h).toFixed(2);
              }
              this.showP = rr.prizeInfos.filter((v) => {
                return v.state == 1;
              });
              console.log(this.showP)
              let a = this.showP.filter((v) => {
                return v.type != 0;
              });
              let b = this.showP.filter((v) => {
                return v.type == 0;
              });
              let sortrule = (a, b) => {
                return a.type - b.type;
              };
              a.sort(sortrule);
              this.showP = a.concat(b);
              // console.log(this.showP);
              this.$forceUpdate();
            } else {
              this.LDData = {
                lotteryRule: "",
                matchId: "",
                prizeInfos: [{
                  name: "谢谢参与",
                  prizeImg: "",
                  num: "",
                  state: 1,
                  prizeProb: 100,
                  type: "",
                  wc: 1,
                }, ],
                et: "",
                st: "",
              };
            }
            // console.log(this.LDData);
          });
      },
      // 查看抽奖记录
      seeLdRecord() {
        console.log(this.LDData.id)
        this.$router.push({
          path: "/match/extend/guess/ldRecord?" + this.$Base64.encode(6)
        });
      },
      // 查看抽奖人员
      goPer() {
        this.$router.push({
          path: "/match/extend/guess/ldper",
          query: {
            id: this.matchId,
          },
        });
      },
      // 保存
      save() {
        let that = this;
        let tt = that.LDData.prizeInfos;
        // console.log(that.LDData);
        if (!tt) {
          that.$message.warning("请设置奖品");
          return false;
        }
        setTimeout(() => {
          let oo = tt.filter((v) => v.state == 1);
          if (that.LDData.st && that.LDData.et) {
            that.LDData.startTime = new Date(that.LDData.st).getTime();
            that.LDData.endTime = new Date(that.LDData.et).getTime();
            if (that.LDData.startTime > that.LDData.endTime) {
              that.$message.warning("结束时间需大于开始时间");
              return false;
            }
            if (oo.length != 8) {
              that.$message.warning("显示数量需为8条");
            } else {
              if (that.Deployment > 0) {
                that.$message.warning("概率未分配完成，请调整");
                return false;
              }
              tt.forEach((v) => {
                if (that.luckType == 'X') v.matchId = that.matchId;
                v.type = Number(v.type);
              });
              // that.LDData.groupId = "";
              if (that.luckType == 'X') that.LDData.matchId = that.matchId;
              else that.LDData.matchId = that.matchIds.join(',')
              // 修改保存
              console.log(that.LDData)
              that.LDData.type = that.luckType // (X:竞猜比赛选手的成绩;F:判断本人成绩,完赛则有抽奖资格)
              // return
              if (that.LDData.id) {
                that.bsave(that.LDData);
              } else {
                // 添加保存
                that.asave(that.LDData);
              }
            }
          } else {
            that.$message.warning("请选择活动日期");
          }
        }, 250);
      },
      // 添加保存
      asave(obj) {
        // console.log(JSON.stringify(obj))
        this.$axios.post("/sbr/guess/addLottery", obj).then((res) => {
          this.$alert("添加成功", "提示", {
            confirmButtonText: "确定",
            showClose: false,
            closeOnClickModal: false,
            type: "success",
            callback: (action) => {
              if (action == "confirm") {
                // this.$router.push("/luckyDraw");
                if (that.luckType == 'X') this.getALd();
                else that.$emit('onclose')
              }
            },
          });
        });
      },
      // 修改保存
      bsave(obj) {
        this.$axios
          .put("/sbr/guess/putLottery", obj)
          .then((res) => {
            this.$message.success("修改成功");
            if (this.luckType == 'X') this.getALd();
            else this.$emit('onclose')
          })
        // .catch((err) => {
        //   this.$message.error("修改失败");
        // });
      },
      delLine(i) {
        this.LDData.prizeInfos.splice(i, 1);
        let n = 0;
        // console.log(this.LDData.prizeInfos);
        for (let a = 0; a < this.LDData.prizeInfos.length - 1; a++) {
          if (this.LDData.prizeInfos[a].state == 1) {
            // n += Number(this.LDData.prizeInfos[a].prizeProb);
            n = floatAdd(n, Number(this.LDData.prizeInfos[a].prizeProb));
          }
        }
        if (1 - n < 0) {} else {
          this.LDData.prizeInfos[
            this.LDData.prizeInfos.length - 1
          ].prizeProb = Number(1 - n).toFixed(2);
        }
        this.$forceUpdate();
      },
      // 添加奖品
      addJP() {
        let obj = {
          name: "",
          prizeImg: "",
          num: "",
          prizeProb: "",
          prizeLinks: "",
          state: 0,
          type: "",
          wc: 1,
        };
        // this.tableData.push(obj);
        this.LDData.prizeInfos.splice(this.LDData.prizeInfos.length - 1, 0, obj);
      },
      // 查询赛事列表
      getMatch() {
        let q = {
          name: "",
          type: "",
          state: "",
          startDate: "",
          endDate: "",
        }
        let oo = this.$Base64.encode("orgId=" + this.$orgId);
        oo = this.$Base64.encode(oo);
        this.$axios
          .get("/sbr/match/getMatchsApp?name=&state=0&type=&place=&date=")
          .then((res) => {
            let rr = res.data.data;
            this.matchArr = rr
          });
      },
      // 根据 id 查询抽奖
      getLotteryById() {
        this.$axios.get('/sbr/guess/getLotteryById?id=' + this.lotteryId).then(res => {
          let rr = res.data.data;
          if (rr) {
            this.matchIds = rr.matchInfos.map(v => {
              return v.id
            })
            rr.et = new Date(rr.endTime);
            rr.st = new Date(rr.startTime);
            // rr.date = [new Date(rr.startTime), new Date(rr.endTime)];
            delete rr.matchInfos
            this.LDData = rr;
            let h = 0;
            rr.prizeInfos.map((v) => {
              // if (v.coun == 0) v.wc = 1;
              if (v.state == 1) {
                h = floatAdd(h, v.prizeProb);
              }
            });
            rr.prizeInfos.forEach((v) => {
              v.type = v.type == 0 ? "" : v.type;
            });
            this.Deployment = 0;
            if (h < 100) {
              this.Deployment = (100 - h).toFixed(2);
            }
            this.showP = rr.prizeInfos.filter((v) => {
              return v.state == 1;
            });
            // console.log(this.showP)
            let a = this.showP.filter((v) => {
              return v.type != 0;
            });
            let b = this.showP.filter((v) => {
              return v.type == 0;
            });
            let sortrule = (a, b) => {
              return a.type - b.type;
            };
            a.sort(sortrule);
            this.showP = a.concat(b);
            // console.log(this.showP);
            this.$forceUpdate();
          }
        })
      }
    },
    mounted() {
      let m = sessionStorage.getItem("MandA")
      if (m) {
        mId = this.$Base64.decode(m);
        this.matchId = this.$Base64.decode(m);
      }
      if (this.luckType == 'X') this.getALd();
      else this.getMatch()
    },
  };
</script>

<style scoped>
  .addBox {
    width: 100%;
  }

  .addBox .inbBox {
    overflow: hidden;
  }

  .addBox .in-b {
    float: left;
    margin-bottom: 15px;
  }

  .addBox .in-b:first-child {
    margin-right: 20px;
  }

  .addBox .in-b.btn-see {
    margin-left: 20px;
  }

  .addBox .in-b span {
    float: left;
    margin-right: 10px;
    line-height: 40px;
  }

  .en {
    float: left;
    width: 250px;
  }

  .tips {
    overflow: hidden;
    width: 100%;
  }

  .tab {
    width: 100%;
    margin-top: 20px;
    overflow: hidden;
  }

  .tabBox {
    margin-top: 15px;
  }

  .tabBox>>>.el-table__row td {
    padding: 0;
  }

  .actI {
    margin-right: 10px;
  }

  .changeLogo {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 50px;
    height: 50px;
    margin: 5px auto;
  }

  .changeLogo:hover {
    border-color: #409eff;
  }

  .changeLogo .chooseIpt {
    position: absolute;
    width: 50px;
    height: 50px;
    opacity: 0;
    top: 0;
    left: 0;
    cursor: pointer;
  }

  .changeLogo input {
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }

  .seeLogo {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 50px;
    height: 50px;
    margin: 5px auto;
  }

  .seeLogo img {
    width: 100%;
    height: 100%;
  }

  .seeLogo .avatar-uploader-icon {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    z-index: -1;
    color: white;
    background-color: rgba(0, 0, 0, 0.4);
  }

  .seeLogo:hover .avatar-uploader-icon {
    z-index: 2;
    opacity: 1;
  }

  .sbb {
    width: 100%;
    overflow: hidden;
    margin-top: 15px;
    text-align: center;
  }

  .tabTips {
    width: 100%;
    font-size: 14px;
    line-height: 30px;
    color: red;
  }

  .dw {
    line-height: 40px;
    font-size: 16px;
    color: #000;
  }

  .sheng {
    color: #16c95d;
    font-size: 18px;
  }

  .demo {
    width: 260px;
    height: 260px;
    /* float: left; */
    background-color: #16cd82;
    border-radius: 10px;
    padding: 20px;
  }

  .item {
    width: 80px;
    height: 80px;
    border-radius: 10px;
    /* background-color: yellowgreen; */
    background-color: #fff;
    overflow: hidden;
    float: left;
    line-height: 80px;
    text-align: center;
  }

  .item:nth-child(3n-1) {
    margin: 0 10px;
  }

  .item:nth-child(4) {
    margin: 10px 0;
  }

  .item:nth-child(5) {
    margin: 10px;
  }

  .item:nth-child(6) {
    margin: 10px 0;
  }

  .demoImg {
    width: 80px;
    height: 80px;
    border-radius: 10px;
  }
</style>